package com.xiaoyao.server.web;

import com.xiaoyao.server.entity.User;
import com.xiaoyao.server.service.UserService;
import com.xioayao.server.exception.BizException;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import static org.hamcrest.CoreMatchers.nullValue;

import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Controller
@RequestMapping("/user") // url:/模块/资源/{id}/细分 /seckill/list
public class UserController {

	private final Logger LOG = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private UserService userService;
	public String filePathFir="img/";//实际位置：E:\javaee\Myeclipse\img
	
	
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	//public String list(Model model, Integer offset, Integer limit) {
	public String list(Model model) {
		LOG.info("invoke----------/user/list");
		//offset = offset == null ? 0 : offset;//默认便宜0
		//limit = limit == null ? 50 : limit;//默认展示50条
		List<User> list = userService.getUserList();
		model.addAttribute("userlist", list);
		return "userlist";
	}
	
	
	@RequestMapping("/showUser")
	public String toIndex(HttpServletRequest request,Model model){
		long userId = Integer.parseInt(request.getParameter("id"));
		System.out.println(userId);
		System.out.println("------------------");
		User user = this.userService.getById(userId);
		model.addAttribute("user", user);
		System.out.println(user);
		return "showUser";
	}
	
	@RequestMapping(value ="/login", method = RequestMethod.GET)
	public String login(HttpServletRequest request,Model model){  //登录测试get
		//Model同request.setAttribute("user", user);，只是springmvc这样用
		String name = request.getParameter("name");
		String password = request.getParameter("password");
		User user = this.userService.loginu(name, password);
		model.addAttribute("user", user);
		if(user == null){
			System.out.println("账号或密码错误！");
		}
		else{
			System.out.println(user);
			System.out.println(user.toString());
		}
		//System.out.println(user);
		//request.setAttribute("user", user);
		return "login";
	}
	
	public  boolean isPhone(String mobiles) {//是否是手机号码
		Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0-9]))\\d{8}$");
		Matcher m = p.matcher(mobiles);
		return m.matches();
	}
	
	@RequestMapping(value = "/logint",
	            method = RequestMethod.POST,
	            produces = {"application/json;charset=UTF-8"}
	    )
	@ResponseBody
	public String logint(HttpServletRequest request,Model model){//Model同request.setAttribute("user", user);，只是springmvc这样用@RequestBody String param
		//System.out.println("data:"+param);
		User user = null;
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String phone = username;
		System.out.println("user："+username+"  password："+password);
		if(username != "" && username != null){
			if(isPhone(phone)){	//是否是手机号码
				user = this.userService.loginp(phone, password);
				System.out.println("phone:"+phone+" "+ password);
			}
			else{
				user = this.userService.loginu(username, password);
				System.out.println("name:"+username+" "+ password+" ");
			}
		}

		if(user == null){
			System.out.println("账号或密码错误！");
			return "账号或密码错误！";
		}
		else{
			System.out.println(user);
			return user.toString();
		}
        //model.addAttribute("user", user);
        
		//request.setAttribute("user", user);
		//return user;
	}
	
	//修改头像
	@RequestMapping(value = "/alterAvatarUrl",
            method = RequestMethod.POST,
            produces = {"application/json;charset=UTF-8"}
    )
	@ResponseBody
	public String alterAvatarUrl(MultipartFile file) throws IOException{
		if(file!=null){
	        String fileName = file.getOriginalFilename();  
	        String id = fileName.substring(0,fileName.lastIndexOf("."));
	        System.out.println("fileName:"+fileName+" id: "+id);
	        //UUID uid = UUID.randomUUID();//唯一标识 
	        String newFileName = fileName;  //uid+fileName
	        //System.out.println("newFileName:"+newFileName);
	        File descfile = new File(filePathFir, newFileName);// 文件路径文件名  
	        try{
	        	FileUtils.copyInputStreamToFile(file.getInputStream(), descfile);// 开始上传  
	        	//file.transferTo(descfile);
	        	System.out.println(newFileName+"上传成功");
	        }catch(Exception e){
	        	System.out.println(newFileName+"上传失败! "+e.toString());
	        	return "0";
	        }
	        String avatarUrl = newFileName;
	        long userid = Long.parseLong(id);
	        System.out.println("avatarUrl="+avatarUrl+" id= "+userid);
	        
			int flag = this.userService.alterAvatarUrl(userid, avatarUrl);
			
			if(flag==1){
				System.out.println("修改成功");
				return "1";
			}
			else{
				System.out.println("修改失败");
				return "0";
			}
		}
		else{
			return "0";
		}
	}
	
	//修改姓名
	@RequestMapping(value = "/alterName",
            method = RequestMethod.POST,
            produces = {"application/json;charset=UTF-8"}
    )
	@ResponseBody
	public String alterName(HttpServletRequest request,Model model){
		long userid = Integer.parseInt(request.getParameter("userid"));
		String username = request.getParameter("username");
		System.out.println("id："+userid+"  username："+username);
		try{
			int flag = this.userService.alterName(userid, username);
		
			if(flag==1){
				System.out.println("修改成功");
				return "1";
			}
			else{
				System.out.println("修改失败");
				return "0";
			}
		}catch (Exception e) {
			System.out.println("用户名重复");
			return "0";
		}
	}	
	
	//修改手机号码
	@RequestMapping(value = "/alterPhone",
            method = RequestMethod.POST,
            produces = {"application/json;charset=UTF-8"}
    )
	@ResponseBody
	public String alterPhone(HttpServletRequest request,Model model){
		long userid = Integer.parseInt(request.getParameter("userid"));
		String phone = request.getParameter("phone");
		System.out.println("id："+userid+"  phone："+phone);
		try{
			int flag = this.userService.alterPhone(userid, phone);
		
			if(flag==1){
				System.out.println("修改成功");
				return "1";
			}
			else{
				System.out.println("修改失败");
				return "0";
			}
		}catch (Exception e) {
			System.out.println("修改失败");
			return "0";
		}
	}
	
	//修改手机号码
	@RequestMapping(value = "/getHeadPhoto",
            method = RequestMethod.GET,
            produces = {"application/json;charset=UTF-8"}
    )
	@ResponseBody
	public String getHeadPhoto(HttpServletRequest request,HttpServletResponse response,Model model){
		long userid = Integer.parseInt(request.getParameter("userid"));
		String headPhoto="";//"1.jpg"
		System.out.println("userid："+userid);
		try{
			headPhoto = this.userService.getHeadPhoto(userid);
			System.out.println("HeadPhoto:"+headPhoto);
			
			if(headPhoto.equals(null)&&headPhoto.equals("null")){
				System.out.println("Database no find, HeadPhoto:null");
				return "0";
			}
			else{
				try{
					request.setCharacterEncoding("UTF-8");  
					BufferedInputStream bis = null;  
					BufferedOutputStream bos = null;  		   			
					//获取下载文件路径
					String downLoadPath = filePathFir + headPhoto;	
					File headPhotoF = new File(downLoadPath);  	
					if(headPhotoF.exists()){
						//获取文件的长度  
						long fileLength = headPhotoF.length(); 
						 //设置文件输出类型
					    response.setContentType("application/octet-stream");  
					    response.setHeader("Content-disposition", "attachment; filename="  
					        + new String(headPhoto.getBytes("utf-8"), "ISO8859-1")); 
					    //设置输出长度
					    response.setHeader("Content-Length", String.valueOf(fileLength));  
					    //获取输入流
					    bis = new BufferedInputStream(new FileInputStream(downLoadPath));  
					    //输出流
					    bos = new BufferedOutputStream(response.getOutputStream());  
					    byte[] buff = new byte[2048];  
					    int bytesRead;  
					    while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {  
					      bos.write(buff, 0, bytesRead);  
					    }  	
					    //关闭流
					    bis.close();  
					    bos.close();
					    return "1";
					}else{
						System.out.println("无此文件！");
						return "1";
					}
				}catch (Exception e) {
					System.out.println("获取失败"+e.toString());
					return "0";
				}	
			}
		}catch (Exception e) {
			System.out.println("getHeadPhoto error:"+e.toString());
			return "0";
		}

	}	
	
}
